package com.shuo.juc.latch;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 精简版CountDownLatch
 */
public class GGCountDownLatch {

    // sync作为代理
    private final GGCountDownLatch.Sync sync;

    public GGCountDownLatch(int count) {
        // count == AQS.state
        this.sync = new GGCountDownLatch.Sync(count);
    }

    public void await() throws InterruptedException {
        // 最后阻塞在parkAndCheckInterrupt, 追到底层就是靠park来阻塞
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    public void countDown() {
        // 追到底层是用了unpark来解除await的阻塞
        sync.releaseShared(1);
    }

    private static final class Sync extends AbstractQueuedSynchronizer {

        Sync(int count) {
            setState(count);
        }

        protected int tryAcquireShared(int acquires) {
            // count为0时才可以获得锁
            return (getState() == 0) ? 1 : -1;
        }

        protected boolean tryReleaseShared(int releases) {
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c - 1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }


}
